package com.example.lawyer.netty;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.lawyer.R;
import com.example.lawyer.datavar.OverallData;
import com.example.lawyer.netty.data.CHECKMessageData;
import com.example.lawyer.netty.data.NettyMessageData;
import com.example.lawyer.service.NettyService;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyStart
{


    public void Start(NettyService service, OverallData data) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(nioEventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY,true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
        bootstrap.handler(new NettyInit(service));
        bootstrap.remoteAddress("192.168.1.6",9999);

        ChannelFuture sync = bootstrap.connect().sync();
        Channel channel = sync.channel();
        data.setChannel(channel);
        SendCheck(channel,data);
        System.out.println("启动结束");

    }


    private void SendCheck(Channel channel,OverallData data)
    {

        if(data.getToken()==null)
        {
            System.out.println("令牌空");
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        NettyMessageData messageData = new NettyMessageData();
        messageData.receiveid = 19251931413L;
        messageData.types = "CHECK";
        messageData.times = simpleDateFormat.format(new Date());
        CHECKMessageData checkMessageData = new CHECKMessageData();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(1);
        Random random = new Random();
        for(int s=0;s<8;s++)
        {
            int i = random.nextInt(9);
            stringBuffer.append(i);
        }
        checkMessageData.id = stringBuffer.toString();
        checkMessageData.context =data.getToken();
        messageData.massage = checkMessageData;

        Gson gson = new Gson();
        String s = gson.toJson(messageData);
        channel.write(s);
        NettyConfig.ChanneGroup= channel;

    }

}
